package com.cdtye.shuoh.config.netty;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;

import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.timeout.IdleStateHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import java.nio.ByteOrder;
import java.util.concurrent.TimeUnit;


@Component
@ConditionalOnProperty(value = "netty.enabled", havingValue = "true")
public class NettyStart {
    @Resource
    private ServerHandler serverHandler;
    private EventLoopGroup bossGroup = new NioEventLoopGroup();
    private EventLoopGroup workGroup = new NioEventLoopGroup();

    @Value("${netty.port}")
    private Integer port;

    private static final Logger LOGGER = LoggerFactory.getLogger(NettyStart.class);

    /**
     * 启动netty服务
     * @throws InterruptedException
     */
    @PostConstruct
    public void start() throws InterruptedException {
        ServerBootstrap b=new ServerBootstrap();
        b.group(bossGroup,workGroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG,128)
                .childHandler(new ChannelInitializer<SocketChannel>()  {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        //增加心跳检测
                        //增加帧长度校验，解决TCP拆包粘包的bug
                        socketChannel.pipeline().addLast(new LengthFieldBasedFrameDecoder(ByteOrder.LITTLE_ENDIAN,65535,2,2,23,0,Boolean.TRUE));
                        socketChannel.pipeline().addLast(new MyDecoder());
                        socketChannel.pipeline().addLast(new MyEncoder());
                        socketChannel.pipeline().addLast(new IdleStateHandler(5,5,5, TimeUnit.MINUTES));
                        socketChannel.pipeline().addLast(serverHandler);
                    }
                });
        ChannelFuture future = b.bind("0.0.0.0",port).sync();//开启需要监听 的端口
        if (future.isSuccess()) {
            LOGGER.info("-------------------------------------netty服务"+port+"启动成功--------------------------------------------");
        }
    }

    /**
     * 销毁
     */
    @PreDestroy
    public void destroy() {
        bossGroup.shutdownGracefully().syncUninterruptibly();
        workGroup.shutdownGracefully().syncUninterruptibly();
        LOGGER.info("关闭 Netty 成功");
    }
}


